package com.example.community.service.Impl;

import com.example.community.dao.pojo.User;
import com.example.community.service.RegisterService;
import com.example.community.service.UserService;
import com.example.community.uitls.CommunityUtil;
import com.example.community.uitls.MailClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import static com.example.community.uitls.CommunityConstant.*;

/**
 * @ClassName: LoginServiceImpl
 * @Description:
 * @Author
 * @Date 2022-03-17
 * @Version 1.0
 */
@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private UserService userService;


    @Value("${community.path.domain}")
    private String domain;

//    @Value("${server.servlet.context-path}")
//    private String contextPath;


    /**
     * 注册功能
     * @param user
     * @return
     */

    public Map<String,Object> register(User user){
        HashMap<String, Object> map = new HashMap<>();
        if (user==null){
            throw new IllegalArgumentException("参数不能为空");
        }
        //判断账号、密码、邮箱是否为空
        if (StringUtils.isBlank(user.getUsername())){
            map.put("usernameMeg","账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空!");
            return map;
        }
        // 验证账号和邮箱是否已经存在
        User u = userService.findUserByUsername(user.getUsername());
        if (u!=null){
            map.put("usernameMsg", "该账号已存在!");
            return map;
        }
        u = userService.findUserByEmail(user.getEmail());
        if (u!=null){
            map.put("emailMsg", "该邮箱已被注册!");
            return map;
        }
        //注册用户
        user.setCreateTime(new Date());
        user.setSalt(CommunityUtil.generateUUID().substring(0,5));
        user.setPassword(CommunityUtil.md5(user.getPassword()+ user.getSalt()));
        user.setStatus(0);
        user.setType(0);
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        userService.insertUser(user);

        User user1 = userService.findUserByEmail(user.getEmail());

        //发送激活邮件
        Context context = new Context();
        context.setVariable("email",user.getEmail());
        String url = domain  +"/activation/" + user1.getId() + "/" + user.getActivationCode();
        context.setVariable("url",url);
        String content = templateEngine.process("/mail/activation", context);
        mailClient.sendMail(user.getEmail(),"激活账号",content);

        return map;
    }

    /**
     * 激活账号功能
     * @param userId
     * @param code
     * @return
     */
    @Override
    public int activation(int userId, String code) {
        User user = userService.findUserById(userId);
        if (user.getStatus() == 1) {
            return ACTIVATION_REPEAT;
        } else if (user.getActivationCode().equals(code)) {
            userService.updateActivationCode(userId, 1);
            userService.clearCache(userId);
            return ACTIVATION_SUCCESS;
        } else {
            return ACTIVATION_FAILURE;
        }
    }

    /**
     * 登录验证功能
     */
}
